<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Group gateway class for communicating with persistent storage
 *
 * @category    RedCross
 * @package     Core_Gateway
 */
class Core_Gateway_Group extends RedCross_Gateway_GatewayAbstract
{
    /**
     * Constructor
     * Defines some private variables
     */
    public function __construct()
    {
        $this->_class = 'Group';
        $this->_modelPath = 'Core_Model';
    }

    public function fetchById($id)
    {
        $result = Doctrine_Query::create()
            ->select()
            ->from($this->getModelClass() .' g')
            ->leftJoin('g.Users u')
            ->leftJoin('u.Member m')
            ->where('g.id = ?', $id)
            ->fetchOne();
        return $result;
    }

    public function fetchGroupNameById($id)
    {
        $result = Doctrine_Query::create()
            ->select()
            ->from($this->getModelClass() .' g')
            ->where('g.id = ?', $id)
            ->fetchOne(null, Doctrine_Core::HYDRATE_ARRAY);
        return $result;
    }

    public function addUser($groupId, $userId)
    {
        $userGroup = new RedCross_Gateway_Base_UserGroup();
        $userGroup->user_id = $userId;
        $userGroup->group_id = $groupId;
        $userGroup->save();
        return true;
    }

    public function removeUser($groupId, $userId)
    {
        $group = $this->fetchById($groupId);
        if (!$group) return false;
        $group->unlink('Users', $userId, true);
        return true;
    }
}
